package cookies.exercises;

import cookies.utils.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-07-30
 * Time:3:24
 */
@WebServlet(name = "LoginUI", urlPatterns = "/loginUI")
public class LoginUI extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie username = Utils.getCookie(req, "username");
        Cookie pwd = Utils.getCookie(req, "pwd");
        String usernameValue = "";
        String pwdValue = "";
        if (username != null && pwd != null) {
            usernameValue = username.getValue();
            pwdValue = pwd.getValue();
        }

        BufferedReader bw = new BufferedReader(new FileReader("C:\\Users\\22954\\Desktop\\IDEA\\java-web\\Cookie-Learning\\src\\main\\java\\cookies\\exercises\\login.html"));
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        String line;
        while ((line = bw.readLine()) != null) {
            if(line.contains("username")) {
                line  = line.replace("\"\"", '"' + usernameValue + '"');
            }
            if(line.contains("pwd")) {
                line  = line.replace("\"\"", '"' + pwdValue + '"');
            }
            out.println(line);
        }
        bw.close();
        out.flush();
        out.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
